package com.ljfiction.book.fragment;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.google.gson.Gson;
import com.google.gson.JsonSyntaxException;
import com.ljfiction.book.Baner.FensiRankBean;
import com.ljfiction.book.MyView.CircularImageView;
import com.ljfiction.book.MyView.DividerItemDecoration;
import com.ljfiction.book.R;
import com.ljfiction.book.activitys.UserCenterActivity;
import com.ljfiction.book.adapter.FensiRankAdapter;
import com.ljfiction.book.http.HttpManager;
import com.ljfiction.book.tools.ScreenUtils;
import com.ljfiction.book.tools.SettingManager;
import com.lzy.okhttputils.OkHttpUtils;
import com.lzy.okhttputils.callback.StringCallback;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.listener.OnRefreshLoadMoreListener;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.Unbinder;
import okhttp3.Call;
import okhttp3.Response;

/**
 * Created by Android on 2017/11/6.
 */

public class FensiAllRankfragment extends BaseFragment {
    @BindView(R.id.fensirecycle)
    RecyclerView fensirecycle;
    Unbinder unbinder;
    @BindView(R.id.refresh_fensi)
    SmartRefreshLayout refreshFensi;
    private String bookId;
    private int type = 0;//0是总榜，1是周榜
    private int page = 1;
    private FensiRankBean fensiRankBean;
    private Context context;
    private FensiRankAdapter fensiRankAdapter;
    private List<FensiRankBean.DataBean.ListBean> firstlistData = new ArrayList<>();
    private List<FensiRankBean.DataBean.ListBean> listData = new ArrayList<>();
    private View headView;
    private ViewHolder viewHolder;
    private Intent intent;

    public FensiAllRankfragment newInstance(String bookId, int type) {
        FensiAllRankfragment fensiAllRankfragment = new FensiAllRankfragment();
        Bundle bundle = new Bundle();
        bundle.putString("bookId", bookId);
        bundle.putInt("type", type);
        fensiAllRankfragment.setArguments(bundle);
        return fensiAllRankfragment;
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fensi_fragment, null);
        unbinder = ButterKnife.bind(this, view);
        Bundle args = getArguments();
        if (args != null) {
            this.bookId = args.getString("bookId");
            this.type = args.getInt("type", 0);
        }
        context = getContext();
        intent = new Intent(context, UserCenterActivity.class);
        intView();
        intData();
        return view;
    }

    private void intView() {
        fensiRankAdapter = new FensiRankAdapter(R.layout.fensirank_item, listData);
        headView = LayoutInflater.from(context).inflate(R.layout.fensirank_headview, null);
        viewHolder = new ViewHolder(headView);
        viewHolder.oneimageFensirank.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (firstlistData.size()<2)return;
                intent.putExtra("userId", String.valueOf(firstlistData.get(1).getUserId()));
                startActivity(intent);
            }
        });
        viewHolder.towimageFensirank.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (firstlistData.size()<1)return;
                intent.putExtra("userId", String.valueOf(firstlistData.get(0).getUserId()));
                startActivity(intent);
            }
        });
        viewHolder.threeimageFensirank.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (firstlistData.size()<3)return;
                intent.putExtra("userId", String.valueOf(firstlistData.get(2).getUserId()));
                startActivity(intent);
            }
        });
        headView.setLayoutParams(new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT));
        fensirecycle.setAdapter(fensiRankAdapter);
        fensirecycle.setLayoutManager(new LinearLayoutManager(context));
        fensirecycle.addItemDecoration(new DividerItemDecoration(context, DividerItemDecoration.VERTICAL_LIST));
        fensiRankAdapter.setOnItemChildClickListener(new BaseQuickAdapter.OnItemChildClickListener() {
            @Override
            public void onItemChildClick(BaseQuickAdapter adapter, View view, int position) {
                intent.putExtra("userId", String.valueOf(listData.get(position).getUserId()));
                startActivity(intent);
            }
        });
        refreshFensi.setOnRefreshLoadMoreListener(new OnRefreshLoadMoreListener() {
            @Override
            public void onLoadMore(RefreshLayout refreshlayout) {
                if (fensiRankBean.getData().isIsLastPage()) {
                    refreshFensi.finishLoadMore();
                    refreshFensi.setEnableLoadMore(false);
                } else {
                    page++;
                    intData();
                }
            }

            @Override
            public void onRefresh(RefreshLayout refreshlayout) {
                page = 1;
                refreshFensi.setEnableLoadMore(true);
                intData();
            }
        });
        fensiRankAdapter.addHeaderView(headView);
    }

    private void intData() {
        if (type == 1) {
            OkHttpUtils.get(HttpManager.IP + "/fans-bookFansWeek/" + bookId + "/" + page)

                    .execute(new StringCallback() {
                        @Override
                        public void onSuccess(String s, Call call, Response response) {
                            refreshFensi.finishLoadMore();
                            refreshFensi.finishRefresh();
                            Gson gson = new Gson();
                            try {
                                fensiRankBean = gson.fromJson(s, FensiRankBean.class);
                                if (fensiRankBean.getReturnCode() == 200) {
                                    if (page == 1) {
                                        firstlistData.clear();
                                        listData.clear();
                                        firstlistData.addAll(fensiRankBean.getData().getList());
                                        for (int i = 0; i < firstlistData.size(); i++) {
                                            if (i > 2) {
                                                listData.add(firstlistData.get(i));
                                            }
                                        }
                                        toheadview();
                                    } else {
                                        listData.addAll(fensiRankBean.getData().getList());
                                    }
                                    fensiRankAdapter.notifyDataSetChanged();
                                }
                            } catch (Exception e) {
                                e.printStackTrace();
                            }
                        }
                    });
        } else {
            OkHttpUtils.get(HttpManager.IP + "/fans-bookFansTotal/" + bookId + "/" + page)

                    .execute(new StringCallback() {
                        @Override
                        public void onSuccess(String s, Call call, Response response) {
                            refreshFensi.finishLoadMore();
                            refreshFensi.finishRefresh();
                            Gson gson = new Gson();
                            try {
                                fensiRankBean = gson.fromJson(s, FensiRankBean.class);
                                if (fensiRankBean.getReturnCode() == 200) {
                                    if (page == 1) {
                                        firstlistData.clear();
                                        listData.clear();
                                        firstlistData.addAll(fensiRankBean.getData().getList());
                                        if (firstlistData.size() > 3) {
                                            for (int i = 0; i < firstlistData.size(); i++) {
                                                if (i > 2) {
                                                    listData.add(firstlistData.get(i));
                                                }
                                            }
                                        }
                                        toheadview();
                                    } else {
                                        listData.addAll(fensiRankBean.getData().getList());
                                    }
                                    fensiRankAdapter.notifyDataSetChanged();
                                }
                            } catch (Exception e) {
                                e.printStackTrace();
                            }
                        }
                    });
        }
    }

    private void toheadview() {
        switch (firstlistData.size()) {
            case 0:
                viewHolder.onefensi.setVisibility(View.INVISIBLE);
                viewHolder.towfensi.setVisibility(View.INVISIBLE);
                viewHolder.threefensi.setVisibility(View.INVISIBLE);

                break;
            case 1:
                viewHolder.towfensi.setVisibility(View.VISIBLE);
                viewHolder.onefensi.setVisibility(View.INVISIBLE);
                viewHolder.threefensi.setVisibility(View.INVISIBLE);
                viewHolder.townameFensirank.setText(firstlistData.get(0).getUserName());
                viewHolder.townumFensirank.setText(String.valueOf(firstlistData.get(0).getFansCount()));
                Glide.with(context).load(firstlistData.get(0).getUserHeadPortraitURL()).override(ScreenUtils.getNum(context,52), ScreenUtils.getNum(context,52)).into(viewHolder.towimageFensirank);
                break;
            case 2:
                viewHolder.towfensi.setVisibility(View.VISIBLE);
                viewHolder.onefensi.setVisibility(View.VISIBLE);
                viewHolder.threefensi.setVisibility(View.INVISIBLE);
                viewHolder.townameFensirank.setText(firstlistData.get(0).getUserName());
                viewHolder.townumFensirank.setText(String.valueOf(firstlistData.get(0).getFansCount()));
                Glide.with(context).load(firstlistData.get(0).getUserHeadPortraitURL()).override(ScreenUtils.getNum(context,52), ScreenUtils.getNum(context,52)).into(viewHolder.towimageFensirank);
                viewHolder.nameoneFensirank.setText(firstlistData.get(1).getUserName());
                viewHolder.onenumFensirank.setText(String.valueOf(firstlistData.get(1).getFansCount()));
                Glide.with(context).load(firstlistData.get(1).getUserHeadPortraitURL()).override(ScreenUtils.getNum(context,42), ScreenUtils.getNum(context,42)).into(viewHolder.oneimageFensirank);
                break;
            default:
                viewHolder.towfensi.setVisibility(View.VISIBLE);
                viewHolder.onefensi.setVisibility(View.VISIBLE);
                viewHolder.threefensi.setVisibility(View.VISIBLE);
                viewHolder.townameFensirank.setText(firstlistData.get(0).getUserName());
                viewHolder.townumFensirank.setText(String.valueOf(firstlistData.get(0).getFansCount()));
                Glide.with(context).load(firstlistData.get(0).getUserHeadPortraitURL()).override(ScreenUtils.getNum(context,52), ScreenUtils.getNum(context,52)).into(viewHolder.towimageFensirank);
                viewHolder.nameoneFensirank.setText(firstlistData.get(1).getUserName());
                viewHolder.onenumFensirank.setText(String.valueOf(firstlistData.get(1).getFansCount()));
                Glide.with(context).load(firstlistData.get(1).getUserHeadPortraitURL()).override(ScreenUtils.getNum(context,42), ScreenUtils.getNum(context,42)).into(viewHolder.oneimageFensirank);
                viewHolder.threenameFensirank.setText(firstlistData.get(2).getUserName());
                viewHolder.threenumFensirank.setText(String.valueOf(firstlistData.get(2).getFansCount()));
                Glide.with(context).load(firstlistData.get(2).getUserHeadPortraitURL()).override(ScreenUtils.getNum(context,42), ScreenUtils.getNum(context,42)).into(viewHolder.threeimageFensirank);
                break;
        }

    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        unbinder.unbind();
    }

    static class ViewHolder {
        @BindView(R.id.oneimage_fensirank)
        CircularImageView oneimageFensirank;
        @BindView(R.id.nameone_fensirank)
        TextView nameoneFensirank;
        @BindView(R.id.onenum_fensirank)
        TextView onenumFensirank;
        @BindView(R.id.towfensi)
        LinearLayout towfensi;
        @BindView(R.id.towimage_fensirank)
        CircularImageView towimageFensirank;
        @BindView(R.id.towname_fensirank)
        TextView townameFensirank;
        @BindView(R.id.townum_fensirank)
        TextView townumFensirank;
        @BindView(R.id.threeimage_fensirank)
        CircularImageView threeimageFensirank;
        @BindView(R.id.threename_fensirank)
        TextView threenameFensirank;
        @BindView(R.id.threenum_fensirank)
        TextView threenumFensirank;
        @BindView(R.id.threefensi)
        LinearLayout threefensi;
        @BindView(R.id.onefensi)
        LinearLayout onefensi;

        ViewHolder(View view) {
            ButterKnife.bind(this, view);
        }
    }
}
